import requests
import json
from typing import Dict, List, Optional
from datetime import datetime, timedelta
import time

class FlightAPI:
    def __init__(self):
        self.base_url = "https://flights.ctrip.com"
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
            'Accept-Encoding': 'gzip, deflate, br',
            'Connection': 'keep-alive',
        }
        
    def get_airports(self) -> Dict[str, Dict]:
        """获取机场信息"""
        # 模拟机场数据
        airports = {
            '北京': {
                'code': 'PEK',
                'name': '北京首都国际机场',
                'city': '北京',
                'coordinates': (116.584, 40.080)
            },
            '上海': {
                'code': 'PVG',
                'name': '上海浦东国际机场',
                'city': '上海',
                'coordinates': (121.805, 31.144)
            },
            '广州': {
                'code': 'CAN',
                'name': '广州白云国际机场',
                'city': '广州',
                'coordinates': (113.299, 23.392)
            },
            '深圳': {
                'code': 'SZX',
                'name': '深圳宝安国际机场',
                'city': '深圳',
                'coordinates': (113.811, 22.639)
            },
            '成都': {
                'code': 'CTU',
                'name': '成都双流国际机场',
                'city': '成都',
                'coordinates': (103.947, 30.578)
            },
            '杭州': {
                'code': 'HGH',
                'name': '杭州萧山国际机场',
                'city': '杭州',
                'coordinates': (120.434, 30.229)
            },
            '南京': {
                'code': 'NKG',
                'name': '南京禄口国际机场',
                'city': '南京',
                'coordinates': (118.872, 31.742)
            },
            '武汉': {
                'code': 'WUH',
                'name': '武汉天河国际机场',
                'city': '武汉',
                'coordinates': (114.208, 30.784)
            }
        }
        
        return airports
    
    def search_flights(self, from_city: str, to_city: str, 
                      date: str = None, return_date: str = None) -> List[Dict]:
        """搜索航班"""
        if not date:
            date = (datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d')
            
        # 这里使用模拟数据，实际需要调用航班查询API
        return self._get_mock_flight_data(from_city, to_city, date, return_date)
    
    def _get_mock_flight_data(self, from_city: str, to_city: str, 
                             date: str, return_date: str = None) -> List[Dict]:
        """模拟航班数据"""
        airports = self.get_airports()
        from_airport = airports.get(from_city, {})
        to_airport = airports.get(to_city, {})
        
        if not from_airport or not to_airport:
            return []
        
        mock_flights = [
            {
                'flight_no': 'CA1801',
                'airline': '中国国际航空',
                'aircraft': 'A320',
                'from_airport': from_airport['code'],
                'to_airport': to_airport['code'],
                'from_city': from_city,
                'to_city': to_city,
                'departure_time': '08:00',
                'arrival_time': '10:30',
                'duration': '2小时30分',
                'price': {
                    'economy': 800,
                    'business': 2400,
                    'first': 4800
                },
                'seats': {
                    'economy': '有',
                    'business': '有',
                    'first': '有'
                },
                'date': date,
                'stops': 0,
                'terminal': 'T3'
            },
            {
                'flight_no': 'MU5101',
                'airline': '中国东方航空',
                'aircraft': 'B737',
                'from_airport': from_airport['code'],
                'to_airport': to_airport['code'],
                'from_city': from_city,
                'to_city': to_city,
                'departure_time': '10:30',
                'arrival_time': '13:00',
                'duration': '2小时30分',
                'price': {
                    'economy': 750,
                    'business': 2250,
                    'first': 4500
                },
                'seats': {
                    'economy': '有',
                    'business': '有',
                    'first': '有'
                },
                'date': date,
                'stops': 0,
                'terminal': 'T2'
            },
            {
                'flight_no': 'CZ3101',
                'airline': '中国南方航空',
                'aircraft': 'A330',
                'from_airport': from_airport['code'],
                'to_airport': to_airport['code'],
                'from_city': from_city,
                'to_city': to_city,
                'departure_time': '14:00',
                'arrival_time': '16:30',
                'duration': '2小时30分',
                'price': {
                    'economy': 720,
                    'business': 2160,
                    'first': 4320
                },
                'seats': {
                    'economy': '有',
                    'business': '有',
                    'first': '有'
                },
                'date': date,
                'stops': 0,
                'terminal': 'T1'
            },
            {
                'flight_no': 'HU7601',
                'airline': '海南航空',
                'aircraft': 'B787',
                'from_airport': from_airport['code'],
                'to_airport': to_airport['code'],
                'from_city': from_city,
                'to_city': to_city,
                'departure_time': '16:30',
                'arrival_time': '19:00',
                'duration': '2小时30分',
                'price': {
                    'economy': 680,
                    'business': 2040,
                    'first': 4080
                },
                'seats': {
                    'economy': '有',
                    'business': '有',
                    'first': '有'
                },
                'date': date,
                'stops': 0,
                'terminal': 'T3'
            }
        ]
        
        return mock_flights
    
    def get_flight_details(self, flight_no: str, date: str) -> Dict:
        """获取航班详细信息"""
        # 模拟航班详情
        details = {
            'flight_no': flight_no,
            'airline': '中国国际航空',
            'aircraft': 'A320',
            'departure_gate': 'A12',
            'arrival_gate': 'B08',
            'departure_terminal': 'T3',
            'arrival_terminal': 'T2',
            'check_in_counter': 'A01-A20',
            'baggage_claim': 'B01',
            'status': '正常',
            'delay_info': '无延误',
            'weather': '晴',
            'temperature': '22°C'
        }
        
        return details
    
    def get_airport_info(self, airport_code: str) -> Dict:
        """获取机场信息"""
        airports = self.get_airports()
        for city, info in airports.items():
            if info['code'] == airport_code:
                return info
        return {}
    
    def get_weather_info(self, city: str) -> Dict:
        """获取天气信息"""
        # 模拟天气数据
        weather_data = {
            'city': city,
            'temperature': '22°C',
            'weather': '晴',
            'humidity': '65%',
            'wind': '东南风 3级',
            'visibility': '10km',
            'pressure': '1013hPa'
        }
        
        return weather_data